package initialize

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
	"web/goods/global"
)

// locale参数表示翻译后的目标语言
func InitTrans(locale string) (err error) {
	// 修改gin框架中的validator引擎属性，实现定制
	v, _ := binding.Validator.Engine().(*validator.Validate)
	// 注册一个获取json的tag的自定义方法
	v.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
		if name == "-" {
			return ""
		}
		return name
	})
	zhT := zh.New() // 中文翻译器
	enT := en.New() // 英文翻译器
	// 第一个参数是备用的语言环境，后面的参数是应该支持的语言环境
	uni := ut.New(zhT, zhT, enT)
	// 获取通用的翻译器
	var ok bool
	global.T, ok = uni.GetTranslator(locale)
	if !ok {
		return fmt.Errorf("validator %s not found", locale)
	}

	// 注册进通用翻译器
	switch locale {
	case "en":
		en_translations.RegisterDefaultTranslations(v, global.T)
	case "zh":
		zh_translations.RegisterDefaultTranslations(v, global.T)
	default:
		en_translations.RegisterDefaultTranslations(v, global.T)
	}
	return
}
